const app = getApp();
let pageNo = 1;
let pageSize = 10;
var url = app.data.url;
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    desk: [],
    tips: "提示:选择房间或餐台后请点击锁定!",
    value: "",
    uuid: "",
    merchantId: '',
    show: false,
    key: '',
    value: "",
    checked: false,
    btnType: 0,
    radio: "1",
    id: '',
    unitList: [],
    title: '',
    classId: '',
    fileSavePathItem: [],
    putAwayStatus: true,
    itemPrice: '',
    itemDiscountPrice: '',
    desc: '',
    radio: '0',
  },
  previewImg: function (e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    let imgUrl = item.coverImgPath;
    let _that = this //图片预览
    let imgList = item.pathList;
    wx.previewImage({
      current: imgUrl, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  /**
   * 折扣价
   */
  onDiscountPriceChange: function (event) {
    let _that = this;
    _that.setData({
      itemDiscountPrice: event.detail
    });
  },
  /**
   * 描述
   */
  onDescChange: function (event) {
    let _that = this;
    _that.setData({
      desc: event.detail
    });
  },
  /**
   * 原价
   */
  onPriceChange: function (event) {
    let _that = this;
    _that.setData({
      itemPrice: event.detail
    });
  },
  onPutAwayStatusChange: function (event) {
    let _that = this;
    _that.setData({
      putAwayStatus: event.detail
    });
  },

  onRadioChange: function (event) {
    let _that = this;
    _that.setData({
      radio: event.detail
    });
  },
  /**弹框 */
  onOverLayShow() {
    this.setData({
      overLayShow: true
    });
  },
  /**弹框 */
  onOverLayHide() {
    this.setData({
      overLayShow: false
    });
  },
  /**
   * 上传图片
   */
  afterRead(event) {
    let _that = this;
    const {
      file
    } = event.detail;
    _that.onOverLayShow();
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      wx.uploadFile({
        url: url + '/UploadRecordApi/uploadFile?bucketName=clothes',
        filePath: file[i].path,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        success(res) {
          let result = res.data;
          result = JSON.parse(result);
          console.log(result);
          if (res.statusCode == 200) {
            // 上传成功
            const {
              fileList = []
            } = _that.data;
            fileList.push({
              ...file,
              url: result.data.path
            });
            _that.setData({
              fileList
            });
            let tempItem = result.data.id + "|%|" + result.data.path;
            let fileSavePathItem = _that.data.fileSavePathItem;
            fileSavePathItem.push(tempItem);
            _that.setData({
              fileSavePathItem: fileSavePathItem
            })
            console.log(_that.data.fileSavePathItem);
          } else {
            wx.showToast({
              title: "上传失败!",
              icon: "none",
              duration: 2000
            })
          }
        }
      });
    }
    _that.onOverLayHide();
  },

  /**
   * 删除图片
   */
  deleteImg: function (option) {
    console.log(option);
    let _that = this;
    Dialog.confirm({
      title: '是否删除',
      message: '删除后请点击编辑按钮保存!'
    }).then(() => {
      let index = option.detail.index;
      let imgList = _that.data.fileSavePathItem;
      imgList.splice(index, 1);
      let {
        fileList = []
      } = _that.data;
      fileList.splice(option.detail.index, 1);
      _that.setData({
        fileList: fileList,
        fileSavePathItem: imgList
      });
    }).catch(() => {
      // on cancel
    });
  },

  insertOrUpdate: function (option) {
    console.log(option);
    let _that = this;
    let key = _that.data.key;
    let merchantId = _that.data.merchantId;
    let method = option.currentTarget.dataset.method;
    let fileSavePathItem = JSON.stringify(_that.data.fileSavePathItem);
    let itemPrice = _that.data.itemPrice;
    let itemDiscountPrice = _that.data.itemDiscountPrice;
    let radio = _that.data.radio;
    let classId = _that.data.classId;
    let description = _that.data.value;
    let putAwayStatus = _that.data.putAwayStatus ? 1 : 0
    let tempUrl;
    let tempData;
    if (method == 0) {
      tempUrl = url + '/ClothesSystemApi/addClothesDetail';
      tempData = {
        name: key,
        clothesClassId: classId,
        merchantId: merchantId,
        imgJson: fileSavePathItem,
        originalPrice: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: radio,
        status: putAwayStatus,
        description: description
      }
    } else {
      tempUrl = url + '/ClothesSystemApi/updateClothesDetail';
      let id = _that.data.id;
      tempData = {
        id: id,
        name: key,
        clothesClassId: classId,
        merchantId: merchantId,
        imgJson: fileSavePathItem,
        originalPrice: itemPrice,
        discountPrice: itemDiscountPrice,
        payType: radio,
        status: putAwayStatus,
        description: description
      }
    }
    wx.request({
      url: tempUrl,
      data: tempData,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          _that.setData({
            show: false
          })
          pageNo = 1;
          pageSize = 10;
          _that.queryData(classId, pageNo, pageSize, false);
          wx.showToast({
            title: '操作成功!',
            icon: "success",
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })

  },
  /**表单 start */
  onKeyChange: function (option) {
    let _that = this;
    _that.setData({
      key: option.detail
    })
  },
  onValueChange: function (option) {
    let _that = this;
    _that.setData({
      value: option.detail
    })
  },
  /**
   * 删除
   */
  deleteUnit: function (option) {
    let _that = this;
    let item = option.currentTarget.dataset.item;
    let id = item.id;
    let classId = _that.data.classId;
    let title = item.name;
    Dialog.confirm({
      title: '提醒',
      message: '是否确定删除【' + title + "】"
    }).then(() => {
      wx.request({
        url: url + '/ClothesSystemApi/deleteClothesDetail',
        data: {
          id: id
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.data.code == 200) {
            pageNo = 1;
            pageSize = 10;
            _that.queryData(classId, pageNo, pageSize, false);
            wx.showToast({
              title: "删除成功!",
              icon: "success",
              duration: 2000
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        }
      })
    }).catch(() => {
      // on cancel
    });
  },
  /**表单 end */
  openUnitPop: function (option) {
    let _that = this;
    let type = option.currentTarget.dataset.type;
    let item = option.currentTarget.dataset.item;
    if (type == 1) {
      wx.request({
        url: url + '/ClothesSystemApi/queryClothesDetailById',
        data: {
          id: item.id
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          let detail = res.data.data;
          console.log(detail);
          if (res.data.code == 200) {
            let imgJson = [];
            let fileList = [];
            let imgList = detail.list;
            for (var i = 0; i < imgList.length; i++) {
              let imgVo = imgList[i];
              fileList.push({
                url: imgVo.imgPath
              });
              // 处理多张图片json
              let imgStr = imgVo.imgId + "|%|" + imgVo.imgPath;
              imgJson.push(imgStr);
            }
            _that.setData({
              id: item.id,
              key: item.name,
              fileSavePathItem: imgJson,
              itemPrice: detail.originalPrice,
              itemDiscountPrice: detail.discountPrice,
              radio: detail.payType + '',
              putAwayStatus: detail.status == 1 ? true : false,
              value: detail.description,
              fileList: fileList,
              btnType: 1
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000
            })
          }
        }
      });


    } else {
      _that.setData({
        id: "",
        key: "",
        fileSavePathItem: [],
        itemPrice: "",
        itemDiscountPrice: "",
        radio: '0',
        putAwayStatus: true,
        description: "",
        fileList: [],
        btnType: 0
      })
    }
    _that.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onLoad: function (options) {
    let _that = this;
    let merchantId = options.merchantId;
    let classId = options.classId;
    pageNo = 1;
    _that.queryData(classId, pageNo, pageSize, false);
    _that.setData({
      merchantId: merchantId,
      classId: classId
    })
  },
  queryData: function (classId, pageNo, pageSize, flag) {
    let _that = this;
    wx.request({
      url: url + '/ClothesSystemApi/listPageClothesDetail',
      data: {
        pageSize: pageSize,
        pageNo: pageNo,
        classId: classId,
        invoking: 1
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log("queryData");
        if (res.data.code == 200) {
          console.log(res.data.data);
          if (!flag) {
            _that.setData({
              unitList: res.data.data.pageList
            })
          } else {
            if (res.data.data.pageList.length > 0) {
              _that.setData({
                unitList: _that.data.unitList.concat(res.data.data.pageList)
              })
            }
          }
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })

  },
  changeVal: function (e) {
    let _that = this;
    _that.setData({
      value: e.detail
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    pageNo = 1;
    console.log("onshow");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    pageNo = pageNo + 1;
    let classId = that.data.classId;
    that.queryData(classId, pageNo, pageSize, true);
  },


})